<?php
namespace App\Filters;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;


use App\Models\UserMsgModel;
use App\Filters\JWTFilter;

use Config\Services;

class AuthFilter implements FilterInterface
{
    // 解析token
    // 获取用户id $user_id = AuthLogin::getAccessToken($request);
    public static function getAccessToken($request){
        // 在前后端分离的情况下，不要使用session，因为session无效。
//        $access_token =  $request->headers()['Access-Token'];
        $access_token_obj =  (string)$request->headers()['Access-Token'];
        $access_token = preg_replace("/Access-Token\:\s/",'',$access_token_obj,-1);

        // 去除bearer-
        $access_token = str_replace('bearer-','',$access_token);
         // 解析token
        $pre_user = JWTFilter::parseToken($access_token);

        if($pre_user['status'] && $access_token ) {
            // 返回解析的用户uid;
            // $pre_user['data']['uid']无效
            return $pre_user['data']->uid;
        }else {
            return false;
        }
    }

    // 前置过滤器
    public function before(RequestInterface $request, $arguments = null)
    {
        $userMsgModel = new UserMsgModel();

        $pre_user_id =  AuthFilter::getAccessToken($request);

        if($pre_user_id){
            // 判断帐号是否存在，（并且没有注销）
            $res = $userMsgModel->where('id',$pre_user_id )->find();
            if($res && $res[0]['isDelete'] != '1'){
                $res = $res[0];
                // 判断帐号是否登录token
                if($res['token']){
                    // 不进行拦截
                }else{
                    return Services::response()->setBody( json_encode(['msg'=>'当前未登录！请进行登录','code'=>403]));
                }
            }else{
                return Services::response()->setBody( json_encode(['msg'=>'帐号不存在','code'=>403]));
            }
        }else{
            return Services::response()->setBody(json_encode( ['msg'=>'token错误！无法访问','code'=>403]));
        }
    }

    //--------------------------------------------------------------------
    // 后置过滤器(不能省略)
    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        // Do something here
    }
}